﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ComponentModel;

namespace _8.Base64FileEncryptor
{
    public class Base64StreamEncryptor
    {
        public static void Encrypt(FileStream reader, TextWriter writer)
        {
            int BufSize = 40;
            byte[] bytesBuffer = new byte[BufSize];
            char[] base64CharBuffer = new char[4 * BufSize];
            int readBytesCount;            

            while (true)
            {
                readBytesCount = reader.Read(bytesBuffer, 0, bytesBuffer.Length);
                
                if (readBytesCount == 0)
                {
                    break;
                }

                int convertedCharsCount = Convert.ToBase64CharArray(bytesBuffer, 0, readBytesCount, base64CharBuffer, 0);

                writer.WriteLine(base64CharBuffer, 0, convertedCharsCount);                
            }
        }

        public static void Encrypt(TextReader reader, TextWriter writer)
        {
            int BufSize = 40;
            char[] charsBuffer = new char[BufSize];
            char[] base64CharBuffer = new char[4 * BufSize];
            int readBytesCount;

            while (true)
            {
                readBytesCount = reader.Read(charsBuffer, 0, charsBuffer.Length);

                if (readBytesCount == 0)
                {
                    break;
                }

                var bytes = Encoding.ASCII.GetBytes(charsBuffer, 0, readBytesCount);
                int convertedCharsCount = Convert.ToBase64CharArray(bytes, 0, readBytesCount, base64CharBuffer, 0);

                writer.WriteLine(base64CharBuffer, 0, convertedCharsCount);
            }
        }

        public static void Decrypt(TextReader reader, TextWriter writer)
        {
            while(true)
            {
                string currentLine = reader.ReadLine();

                if (currentLine == null)
                {
                    break;
                }

                byte[] bytes = Convert.FromBase64String(currentLine);

                string originalText = Encoding.ASCII.GetString(bytes);
                writer.Write(originalText);
                
            }
        }
    }
}
